package com.blog.backend.service.impl;

import com.blog.backend.config.RedisValueConfig;
import com.blog.backend.exception.GlobalException;
import com.blog.backend.mapper.BlogAccountMapper;
import com.blog.backend.model.BlogAccount;
import com.blog.backend.req.UserReq;
import com.blog.backend.resp.TokenResult;
import com.blog.backend.service.UserManagerService;
import com.blog.backend.utils.AuthUtils;
import com.blog.backend.config.CodeMsg;
import com.blog.backend.utils.EncryptUtils;
import com.blog.backend.utils.RedisUtils;
import com.blog.backend.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author fanggs
 * @Date 2021/7/12 0012 11:44
 */

@Slf4j
@Service
public class UserManagerServiceImpl implements UserManagerService {


    @Resource
    private BlogAccountMapper blogAccountMapper;

    @Resource
    RedisUtils redisUtils;


    @Override
    public TokenResult login(UserReq req) {
        log.info("登录账号:{}",req.getUsername());
        //校验登录
        BlogAccount account=blogAccountMapper.selectUser(req.getUsername());
        if (ObjectUtils.isEmpty(account)){
            throw new GlobalException(CodeMsg.USER_INFO_ERROR);
        }
        String salt = account.getSalt();
        String asHex = DigestUtils.md5DigestAsHex((salt + req.getPassword()).getBytes());
        if (!asHex.equals(account.getPassword())){
            throw new GlobalException(CodeMsg.USER_PASSWORD_ERROR);
        }
        //登录成功
        String token=null;
        try {
            token = AuthUtils.createToken(account.getAccount(), account.getUserId());
        }catch (Exception e){
            throw new GlobalException(e.getMessage());
        }
        TokenResult result = new TokenResult();
        result.setUserId(account.getUserId());
        result.setUserName(account.getAccount());
        result.setToken(token);
        //将token存入缓存
       redisUtils.set(RedisValueConfig.USER_TOKEN+account.getUserId(),token,RedisValueConfig.expireTime);
        return result;
    }

    @Override
    public String createAccount(UserReq req) {
        BlogAccount account = blogAccountMapper.selectUser(req.getUsername());
        if (!ObjectUtils.isEmpty(account)){
            throw new GlobalException(CodeMsg.USER_INFO_EXIST);
        }
        //创建账号
        BlogAccount newAccount = new BlogAccount();
        newAccount.setAccount(req.getUsername());
        //生成加密盐
        String salt = EncryptUtils.getSalt();
        newAccount.setPassword(DigestUtils.md5DigestAsHex((salt+req.getPassword()).getBytes()));
        newAccount.setUseable((byte) 1);
        newAccount.setSalt(salt);
        newAccount.setUserId(UuidUtils.getId());
        blogAccountMapper.insertSelective(newAccount);
        return req.getUsername();
    }

    @Override
    public Boolean layout(HttpServletRequest request) {
        String token = request.getHeader("token");
        try {
            String verifyToken = AuthUtils.verifyToken(token);
            if (redisUtils.hasKey(RedisValueConfig.USER_TOKEN + verifyToken)){
                redisUtils.del(RedisValueConfig.USER_TOKEN + verifyToken);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
